package tech.yunland.shop.domain.service.report;

import com.moyuer.bsf.common.Convertor;
import com.moyuer.bsf.domain.dao.UserDao;
import com.moyuer.bsf.domain.model.HqlArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.CommissionDao;
import tech.yunland.shop.domain.dao.SaleBillEntryDao;
import tech.yunland.shop.domain.model.SaleBillEntry;
import tech.yunland.shop.domain.model.report.Commission;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.*;

@Service
public class CommissionService {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private CommissionDao commissionDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private UserDao userDao;

	@Autowired
	private SaleBillEntryDao saleBillEntryDao;

	/**
	 * 查询提成月报ListInfo
	 *
	 * @param
	 * @param organId
	 * @return Map<String, Object>
	 * @throws ParseException
	 */
	public List getMonthInfo(String bizDate, String organId) throws ParseException {

		bizDate = bizDate.substring(0, 7);

		String sql = "select user_id,sum(sale) as sale,sum(charge) as charge,sum(commission) as commission from "
				+ "rpt_commission where to_char(biz_date,'yyyy-MM')='" + bizDate + "'and organ_id='" + organId
				+ "' GROUP BY organ_id,user_id ";
		try {
			return jdbcTemplate.queryForList(sql);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}

	}

	/**
	 * 将月报List转换为commission对象
	 * 
	 * @param bizDate
	 * @param organId
	 * @return
	 * @throws ParseException
	 */
	public List<Commission> getMonthCommission(String bizDate, String organId) throws ParseException {

		List<Map<String, Object>> jdbcInfo = this.getMonthInfo(bizDate, organId);

		List<Commission> list = new ArrayList<Commission>();

		for (Map<String, Object> commissionMap : jdbcInfo) {
			Commission commission = new Commission();
			commission.setOrganId(organId);
			Date date = Convertor.parseDate(bizDate);
			commission.setBizDate(date);
			commission.setUser(userDao.get(commissionMap.get("user_id").toString()));
			String sale = commissionMap.get("sale").toString();
			String charge = commissionMap.get("charge").toString();
			String commissionStr = commissionMap.get("commission").toString();

			if (sale.equals(null) || sale.equals(0) || sale.equals("") || sale.equals("0")) {
				commission.setSale(BigDecimal.ZERO);
			} else {
				commission.setSale(new BigDecimal(commissionMap.get("sale").toString()));
			}

			if (charge.equals(null) || charge.equals(0) || charge.equals("") || charge.equals("0")) {
				commission.setCharge(BigDecimal.ZERO);
			} else {
				commission.setCharge(new BigDecimal(commissionMap.get("charge").toString()));
			}

			if (commissionStr.equals(null) || commissionStr.equals(0) || commissionStr.equals("")
					|| commissionStr.equals("0")) {
				commission.setCommission(BigDecimal.ZERO);
			} else {
				commission.setCommission(new BigDecimal(commissionMap.get("commission").toString()));
			}
			list.add(commission);

		}
		return list;
	}

	/**
	 * 获取提成详情对象
	 * 
	 * @param type
	 * @param bizDate
	 * @param organId
	 * @param userId
	 * @param startIdx
	 *@param rows @return
	 */
	public List<SaleBillEntry> getCommissionEntry(String type, String bizDate, String organId, String userId, int startIdx, Integer rows) {

		List<SaleBillEntry> list = new ArrayList<>();

		StringBuffer bufferSQL = new StringBuffer();
		bufferSQL.append(" select DISTINCT id  from  bill_sale_entry where id in ");
		bufferSQL.append(" (select   h.bill_sale_entry_id as id  from bill_sale_handler h  ");
		bufferSQL.append(" left join bill_sale_entry se on h.bill_sale_entry_id=se.id ");
		bufferSQL.append(" left join bill_sale s on s.id=se.owner_id ");
		bufferSQL.append(" where h.handler_id='" + userId + "' and s.organ_id='" + organId + "' AND se.state=1");
		if (type.equals("month")) {
			bizDate = bizDate.substring(0, 7);
			bufferSQL.append(" and to_char(s.bizdate,'yyyy-MM')='" + bizDate + "'  order by s.bizDate desc    )  ");
		} else if (type.equals("day")) {
			bufferSQL.append(" and to_char(s.bizdate,'yyyy-MM-dd')='" + bizDate + "'  order by s.bizDate desc   )  ");
		}
		List<Map<String, Object>> saleBillEntryIds   = saleBillEntryDao.findByNamedParamSQL(bufferSQL.toString(),startIdx,rows,new HashMap<String,Object>());//拿到销售单实体ID
		//List<Map<String, Object>> saleBillEntryIds = jdbcTemplate.queryForList(bufferSQL.toString());//拿到销售单实体ID

		for (Map<String, Object> commissionMap : saleBillEntryIds) {
			SaleBillEntry saleBillEntry = new SaleBillEntry();
			saleBillEntry = saleBillEntryDao.get(commissionMap.get("id").toString());
			list.add(saleBillEntry);
		}

		return list;

	}

	/**
	 * 获取日报对象
	 *
	 * @param id
	 * @return Income
	 */
	public Commission get(String id) {
		return commissionDao.get(id);
	}

	/**
	 * 根据参数生成 hql 查询语句
	 *
	 * @param organId
	 * @param userId
	 * @return
	 * @throws ParseException
	 */
	public HqlArgs genHqlArgs(String bizDate, String userId, String organId) throws ParseException {

		Map<String, Object> args = new HashMap<String, Object>();

		String hql = "from Commission c where 1=1";
		if (organId != null) {
			hql += " and c.organId = :organId ";
			args.put("organId", organId);
		}
		if (userId != null) {
			hql += " and c.user.id = :userId ";
			args.put("userId", userId);
		}
		if (bizDate != null) {
			hql += " and to_char(c.bizDate,'yyyy-MM-dd') = :date ";
			args.put("date", bizDate);
		}

		return new HqlArgs(hql, args);
	}

	/**
	 * 根据入参查询结果数量
	 *
	 * @param userId
	 * @param organId
	 * @return
	 * @throws ParseException
	 */
	public int getResultSize(String bizDate, String userId, String organId) throws ParseException {
		HqlArgs hqlArgs = genHqlArgs(bizDate, userId, organId);
		int count = (int)commissionDao.getCount(hqlArgs.getHql(),hqlArgs.getArgs());
//		int count = commissionDao.findByNamedParam(hqlArgs.getHql(), hqlArgs.getArgs()).size();
		return count;
	}

	/**
	 * 根据入参查询结果集
	 *
	 * @param userId
	 * @param organId
	 * @param startIndex
	 * @param length
	 * @return
	 * @throws ParseException
	 */
	public List<Commission> getResultInfo(String bizDate, String userId, String organId, Integer startIndex,
			Integer length) throws ParseException {

		HqlArgs hqlArgs = genHqlArgs(bizDate, userId, organId);
		String hql = "select c " + hqlArgs.getHql() + " order by c.bizDate desc";

		return commissionDao.findByNamedParam(hql, startIndex, length, hqlArgs.getArgs());
	}

	public int getCommissionEntrySize(String type, String bizDate, String organId, String userId) {
		StringBuffer bufferSQL = new StringBuffer();
		bufferSQL.append(" select count(DISTINCT id) as nums  from  bill_sale_entry where id in ");
		bufferSQL.append(" (select   h.bill_sale_entry_id as id  from bill_sale_handler h  ");
		bufferSQL.append(" left join bill_sale_entry se on h.bill_sale_entry_id=se.id ");
		bufferSQL.append(" left join bill_sale s on s.id=se.owner_id ");
		bufferSQL.append(" where h.handler_id='" + userId + "' and s.organ_id='" + organId + "' ");
		if (type.equals("month")) {
			bizDate = bizDate.substring(0, 7);
			bufferSQL.append(" and to_char(s.bizdate,'yyyy-MM')='" + bizDate + "'  order by s.bizDate desc    )  ");
		} else if (type.equals("day")) {
			bufferSQL.append(" and to_char(s.bizdate,'yyyy-MM-dd')='" + bizDate + "'  order by s.bizDate desc   )  ");
		}
		 Map<String, Object>  records   = saleBillEntryDao.findUniqueBySQL(bufferSQL.toString());
		if(records!=null){
			BigInteger nums = (BigInteger) records.get("nums");
			return nums.intValue();

		}
		return 0;
	}
}
